/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-04-26 13:43:27
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-08-09 14:33:01
 * @FilePath: \ken147258.topayClient\src\plugins\permission.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from "@/router";
import { useUserStore, usePermissionStore, usePayProductStore } from "@/store";
import NProgress from "@/utils/nprogress";
import { RouteRecordRaw, useRoute } from "vue-router";
import { getLoginType } from "@/utils/index";

const loginTypeArr = ['web', 'payee', 'payer'];

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login", "/login/web"];
  const payProductPath = ['/other/channel-management', '/other/channel-order', '/payee/channel-management', '/payee/channel-order',];

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();

    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // debugger
      let loginType = userStore.getLoginType() || getLoginType();

      const hasToken = localStorage.getItem(loginType + "accessToken");
      if (hasToken && loginType) {
        const permissionStore = usePermissionStore();
        if (to.path === "/login") {
          // 如果已登录，跳转首页
          // next({ path: "/" + loginType });
          // next();
          next({ path: to.path + "/" + loginType });
          NProgress.done();
        } else {
          const hasLogin = userStore.user.info?.id || userStore.user.info?.userId;

          if (hasLogin && permissionStore.routes.length) {
            // 未匹配到任何路由，跳转404
            if (to.matched.length === 0) {
              from.name ? next({ name: from.name }) : next("/404");
            } else {
              next();
            }
          } else {
            try {
              await userStore.getUserInfo();

              if (userStore.user.info?.id || userStore.user.info?.userId) {
                const accessRoutes = await permissionStore.generateRoutes();
                // console.log('accessRoutes', accessRoutes)
                accessRoutes.forEach((route: RouteRecordRaw) => {
                  router.addRoute(route);
                });
                if (payProductPath.some(path => to.path.indexOf(path) > -1)) {
                  const payProductStore = usePayProductStore();

                  await payProductStore.loadPayProducts();
                }
                next({ ...to, replace: true });
              } else {
                // ElMessage.error("系统出错");
                next(`/login/` + loginType);
              }
            } catch (error) {
              // 移除 token 并跳转登录页
              if (error.message.indexOf('google验证码') < 0) {
                await userStore.resetToken();
              } else {
                // next(`/login?redirect=${to.path}`);
                next(`/login/` + loginType);
              }
              NProgress.done();
            }
          }
        }
      } else {
        // 未登录可以访问白名单页面
        if (whiteList.indexOf(to.path) !== -1) {
          next();
        } else {
          let path = '/login';
          if (loginTypeArr.includes(loginType)) {
            path += ('/' + loginType);
          }
          // next(`/login?redirect=${to.path}`);
          next(path);

          NProgress.done();
        }
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}

// function getLoginType() {
//   const userStore = useUserStore();
//   let loginType = userStore.getLoginType();

//   if (!loginType) {
//     const id = window.location.pathname.split('/').filter(item => item).shift();
//     userStore.SET_LOGIN_TYPE(id);

//     loginType = userStore.getLoginType();
//   }

//   return loginType;
// }
